package com.atlin.service.impl;

import com.atlin.config.LicenseCheckConfig;
import com.atlin.exception.CustomException;
import com.atlin.license.AbstractServerInfos;
import com.atlin.license.CrossPlatformServerInfos;
import com.atlin.license.LicenseVerify;
import com.atlin.model.LicenseCheckModel;
import com.atlin.model.LicenseContentVo;
import com.atlin.model.LicenseVerifyParam;
import com.atlin.model.ServerInfoModel;
import com.atlin.service.LicenseService;
import de.schlichtherle.license.LicenseContent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * license服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class LicenseServiceImpl implements LicenseService {

    private final LicenseCheckConfig licenseCheckConfig;

    @Override
    public ServerInfoModel getServerInfos() {

        AbstractServerInfos abstractServerInfos = new CrossPlatformServerInfos();

        ServerInfoModel serverInfos = abstractServerInfos.getServerInfos();
        serverInfos.valid();
        return serverInfos;
    }

    /**
     * 导入License
     *
     * @param file License 文件
     */
    @Override
    public LicenseContentVo importLicense(MultipartFile file) {
        if (file == null || file.isEmpty()) {
            throw new CustomException("License 文件为空");
        }

        String licensePath = licenseCheckConfig.getLicensePath();
        String licenseName = licenseCheckConfig.getLicenseName();
        if (StringUtils.isBlank(licensePath)) {
            throw new CustomException("License 配置为空");
        }

        try {
            File dir = new File(licensePath);
            if (!dir.exists() && !dir.mkdirs()) {
                throw new CustomException("无法创建目录: " + licensePath);
            }

            File destFile = new File(dir, licenseName);
            file.transferTo(destFile);

            log.info("License 文件已保存到: {}", destFile.getAbsolutePath());
            return this.licenseInstall();
        } catch (IOException e) {
            log.error("License 文件保存失败: {}", e.getMessage(), e);
            throw new CustomException("License 文件保存失败");
        }
    }

    @Override
    public LicenseContentVo licenseInstall() {
        String licensePath = licenseCheckConfig.getLicensePath();
        String licenseName = licenseCheckConfig.getLicenseName();
        String subject = licenseCheckConfig.getSubject();
        String publicAlias = licenseCheckConfig.getPublicAlias();
        String storePass = licenseCheckConfig.getStorePass();
        String publicKeysStorePath = licenseCheckConfig.getPublicKeysStorePath();

        if (StringUtils.isNotBlank(licensePath) && new File(licensePath).exists()) {
            log.info("++++++++ 开始安装证书 ++++++++");

            LicenseVerifyParam param = new LicenseVerifyParam();
            param.setSubject(subject);
            param.setPublicAlias(publicAlias);
            param.setStorePass(storePass);
            param.setLicensePath(licensePath + File.separator + licenseName);
            param.setPublicKeysStorePath(publicKeysStorePath);

            LicenseVerify licenseVerify = new LicenseVerify();
            //安装证书
            LicenseContent content = licenseVerify.install(param);

            log.info("++++++++ 证书安装结束 ++++++++");
            return buildLicenseContentVo(content);
        }
        return null;
    }

    /**
     * 获取License详情
     */
    @Override
    public LicenseContentVo getLicenseInfo() {
        LicenseVerify licenseVerify = new LicenseVerify();
        LicenseContent content = licenseVerify.verify();
        return buildLicenseContentVo(content);
    }
    
    private LicenseContentVo buildLicenseContentVo(LicenseContent content) {
        LicenseContentVo contentVo = new LicenseContentVo();
        contentVo.setSubject(content.getSubject());
        contentVo.setIssuedTime(content.getIssued());
        contentVo.setExpiryTime(content.getNotAfter());
        contentVo.setDescription(content.getInfo());
        contentVo.setLicenseCheckModel((LicenseCheckModel) content.getExtra());
        return contentVo;
    }

}
